import { makeAutoObservable } from "mobx"

interface UserInfo {
    email: string
    name: string
    role: number
    _id: string
}
export interface UserClass {
    token: string | null
    user: UserInfo
    resetUser(): void
    getLocalInfo(): void
    setLocalInfo({ user, token }: { user: UserInfo, token: string }): void
}
export default class User implements UserClass {
    constructor() {
        // localStorage.setItem()
        if (!this.token) {
            this.getLocalInfo()
        }
        makeAutoObservable(this)
    }

    token = ''
    user = {
        email: "",
        name: "",
        role: 0,
        _id: ''
    }
    resetUser() {
        this.token = ''
        this.user = {
            email: "",
            name: "",
            role: 0,
            _id: ''
        }
        localStorage.clear()
    }
    getLocalInfo() {
        let userRes = JSON.parse(localStorage.getItem('user') || '{}')
        if ((!userRes.token) || (!userRes.user)) {
            this.resetUser()
            return
        }
        this.token = userRes.token
        this.user = userRes.user

        console.log('I got user!!!');

    }
    setLocalInfo({ user, token }: { user: UserInfo, token: string }) {
        let userStr = JSON.stringify({ user, token })
        localStorage.setItem('user', userStr)
        this.token = token
        this.user = user
    }
}